<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace frontend\v1\behaviors;

use yii\filters\auth\QueryParamAuth;
use yii\web\Response;

/**
 * QueryParamAuth is an action filter that supports the authentication based on the access token passed through a query parameter.
 * @author cleverstone
 * @since ym2.0
 */
class QueryParamAuthX extends QueryParamAuth
{
    /**
     * {@inheritdoc}
     */
    public function authenticate($user, $request, $response)
    {
        $accessToken = $request->get($this->tokenParam);
        if (is_string($accessToken)) {
            try {
                $identity = $user->loginByAccessToken($accessToken, get_class($this));
            } catch (\Throwable $e) {
                $response->format = Response::FORMAT_JSON;
                $response->data = [
                    'code' => 500,
                    'msg' => $e->getMessage(),
                ];
                return null;
            }

            if ($identity !== null) {
                return $identity;
            }
        }
        if ($accessToken !== null) {
            $this->handleFailure($response);
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function handleFailure($response)
    {
        if (!empty($response->data)) {
            return;
        }

        $response->format = Response::FORMAT_JSON;
        $response->data = [
            'code' => 401,
            'msg' => 'Your request was made with invalid credentials.',
        ];
    }
}